//=================================================================================================
// DESC: simple parallel programmer for atmel avr 90S2313 / tiny2313
// AUTHOR: wiRe (http://w1r3.de/)
// DATE: 07/04/2006
//
// Copyright (c)2006 wiRe
//=================================================================================================
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>


//-------------------------------------------------------------------------------------------------
#include "pprog.h"
PProg pp;


//-------------------------------------------------------------------------------------------------
#define TINY2313_ID     0x0A911E
#define TINY2313_FUSES  0xFFDF64




//-------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  printf("AVRhvp v1.0 - Copyright (c)2006 wiRe (http://w1r3.de/)\n");

  short port = -1;
  if(argc > 1)
  {
    char *lpszEnd = NULL;
    unsigned long ul = strtoul(argv[1], &lpszEnd, 0);
    if(ul >= (1 << (sizeof(short)*8))) port = -2;
    if(lpszEnd) while(*lpszEnd == ' ' || *lpszEnd == '\t') lpszEnd++;
    if(argc > 2 || (lpszEnd && *lpszEnd) || port == -2)
    {
      printf("error: wrong parameter\nusage: AVRhvp [LPT PORT]\n");
      return(-1);
    }
  }

  try
  {
    pp.init(port);
    printf("lpt base address: %03X\n", pp.get_port());
    printf("\n");

    printf("waiting for signature...\n");
    int sign = pp.read_signature();

    printf("signature: %02X %02X %02X\n", ((sign>>0)&255), ((sign>>8)&255), ((sign>>16)&255));
    printf("fuses: %06X\n", pp.read_fuses());
    printf("lockbits: %02X\n", pp.read_lockbits());
    printf("\n");

    switch(sign)
    {
    case TINY2313_ID:
      printf("TINY2313 detected...\n");
      printf("reset to factory settings...\n");
      for(int n=0; pp.read_fuses() != TINY2313_FUSES; n++)
      {
        if(n >= 5) throw "error: failed to write fuses!";
        pp.write_fuses(TINY2313_FUSES);
      }
      printf("perform chip erase...\n");
      pp.chip_erase();
      break;

    default:
      throw "error: device not supported!";
    }

    pp.terminate();
    printf("\ndone.\n");
  }
  catch(PPerror &ppe)
  {
    printf("error: %s\n", ppe.what());
    pp.terminate();
    return(-1);
  }
  catch(const char *lpsz)
  {
    printf("%s\n", lpsz);
    pp.terminate();
    return(-1);
  }

  return(0);
}
